// import { config } from '@vue/test-utils'
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth'
import router from '@/router'
const TimeOut = 3600
const service = axios.create({
        baseURL: process.env.VUE_APP_BASE_API, // 设置axios请求的基础的基础地址
        timeout: 5000
    })
    // 请求拦截器
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            if (IsCheckTimeOut()) {
                store.dispatch('user/logout')
                router.push('/login')
                return Promise.reject(new Error('TOKEN超时了'))
            }
            config.headers['Authorization'] = `Bearer ${store.getters.token}`
        }
        return config
    }, error => {

        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const { success, message, data } = response.data
        if (success) {
            return data
        } else {
            Message.error(message)
            return Promise.reject(new Error(message))
        }
    }, error => {
        if (error.response && error.response.data && error.response.data.code === 10002) {
            // 当等于10002的时候 表示 后端告诉我token超时了
            store.dispatch('user/logout') // 登出action 删除token
            router.push('/login')
        } else {
            Message.error(error.message) // 提示错误信息
        }
        return Promise.reject(error)
    }
)

function IsCheckTimeOut() {
    var currentTime = Date.now()
    var timeStamp = getTimeStamp()
    const jj = (currentTime - timeStamp) / 1000

    return (currentTime - timeStamp) / 1000 > TimeOut
}
export default service